import React from 'react'
import {connect, actions} from 'mirrorx'
import api from '../../../api'
import {Form, Input, Button, DatePicker, Select} from 'antd'
import RadioGroupWrap from '../component/RadioGroupWrap'
import './index.scss'
import moment from 'moment'

const FormItem = Form.Item
const Option = Select.Option
const RangePicker = DatePicker.RangePicker
const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 8 }
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 16 }
  }
}

class Coupon extends React.Component {
  constructor (props) {
    super(props)
    this.state = {
      qrcode: '',
      showGeneralCode: false,
      showAmountInput: false,
      showReciveInput: false,
      dateArr: [],
      amount: 0,
      store: 0,
      showErr: false,
      availableAmount: 0
    }
    this.onChangeRadio = this.onChangeRadio.bind(this)
    this.handleSubmit = this.handleSubmit.bind(this)
    this.disabledStartDate = this.disabledStartDate.bind(this)
    this.numberValidator = this.numberValidator.bind(this)
    this.couponValueValidator = this.couponValueValidator.bind(this)
    this.reciveValidator = this.reciveValidator.bind(this)
  }
  componentDidMount () {
    // 获取当前渠道余额账户信息
    this.getPartnerAccount()
  }

  getPartnerAccount () {
    T.ajax({
      url: api.getPartnerAccount.path,
      data: {
        partnerId: true // 这个parterId在node端添加的
      }
    }).then(res => {
      if (res.code === 0 && res.data) {
        this.setState({
          availableAmount: res.data.availableAmount
        })
      }
    })
  }
  disabledStartDate (value) {
    let todatay = new Date().getTime()
    todatay -= 24 * 60 * 60 * 1000
    return value < todatay
  }
  couponValueValidator (rule, value, callback) {
    let index = value.indexOf('.')
    console.log('index', index)
    let dotStr = value.slice(index + 1, value.length)
    console.log('value', value)
    if (!value || value < 0 || (index !== -1 && dotStr.length > 2)) {
      callback('Invalid number')
    } else {
      callback()
    }
  }
  numberValidator (rule, value, callback) {
    console.log('store value', value)
    if (!value || value.indexOf('.') > -1 || value < 0) {
      callback('Invalid number')
    } else {
      callback()
    }
  }
  reciveValidator (rule, value, callback) {
    console.log('store value', value)
    const form = this.props.form
    let initStore = form.getFieldValue('initStore')
    console.log('store', initStore)
    console.log('value', value)
    if (Number(value) > Number(initStore)) {
      callback('Recive limit can not be greater than store')
    } else if (!value || value < 0) {
      callback('Invalid number')
    } else {
      callback()
    }
  }
  onChangeRadio (e, type) {
    // type为操作的Radio的分类
    let value = e.target.value
    console.log('value', value)
    if (type === 'amountList') {
      value === 0 && this.setState({showAmountInput: true})
      value === 1 && this.setState({showAmountInput: false})
    }
    if (type === 'reciveList') {
      value === 0 && this.setState({showReciveInput: true})
      value === 1 && this.setState({showReciveInput: false})
    }
  }

  selecteDate (dateArr) {
    let arr = dateArr.map((item) => {
      item = new Date(new Date(item).toLocaleDateString()).getTime()
      return item
    })
    arr[1] += (24 * 60 * 60 * 1000 - 1000)
    console.log('dateArr', arr)
    this.setState({
      dateArr: arr
    })
  }
  handleSubmit (e) {
    e.preventDefault()
    console.log('this.porps', this.props)
    this.props.form.validateFields((err, values) => {
      if (err) return false
      let {dateArr} = this.state
      let userId = ''
      if (this.props.userInfo) {
        userId = this.props.userInfo.userId
      }
      values.effectiveStartDate = dateArr[0]
      values.effectiveEndDate = dateArr[1]
      values.availableStore = values.initStore
      values.partnerId = true
      values.creator = userId

      this.createCoupon(values)
    })
  }
  createCoupon (data) {
    T.ajax({
      url: api.addGoodsPromoBatch.path,
      data: data
    }).then(res => {
      console.log('新增', res)
      if (res.code === 0) {
        actions.routing.push({pathname: '/page-promo-code'})
      }
    })
  }
  render () {
    const {getFieldDecorator} = this.props.form
    let {showAmountInput, showErr, availableAmount, showReciveInput, amount = 0} = this.state
    amount = amount && amount.toFixed(2)
    amount = T.formatPrice(amount)

    let couponTypeList = [
      {name: '1 code 1 person', id: 1},
      {name: 'General', id: 2}
    ]
    let amountList = [
      {name: 'No Limit', id: 1},
      {name: 'Minimum Consumption', id: 0}
    ]
    let reciveList = [
      {name: 'No Limit', id: 1},
      {name: 'Per Person', id: 0}
    ]
    return <div>
      <div className='coupon-create'>
        <div className='nav'>
          <a onClick={() => { actions.routing.push({pathname: '/page-promo-code'}) }}> Marketing</a>  /
           Create
        </div>
        <div className='f20 mt15'>Create</div>
        <Form
          onSubmit={this.handleSubmit}
          className='create-form'>
          {/* 优惠券名称 */}
          <FormItem {...formItemLayout} label='Name'>
            {getFieldDecorator('name', {
              rules: [{
                required: true,
                message: 'Please input name'
              }]
            })(
              <Input maxLength='50' />
          )}
          </FormItem>

          {/*  优惠券类型 */}
          <FormItem
            {...formItemLayout}
            label='Type'>
            {getFieldDecorator('type', {
              rules: [{
                required: true,
                message: 'Please select amount limit'
              }]
            })(
              <RadioGroupWrap
                onChange={(e) => this.onChangeRadio(e, 'couponTypeList')}
                list={couponTypeList} />
          )}
          </FormItem>

          {/* 选择货币单位 */}
          <FormItem
            {...formItemLayout}
            label='Currency'>
            {getFieldDecorator('currency', {
              rules: [{ required: true, message: 'Please select currency' }]
            })(
              <Select placeholder='Please select a country'>
                {
                  ['SGD'].map(item => {
                    return <Option
                      key={item}
                      value={item}>{item}</Option>
                  })
                }
              </Select>
            )}
          </FormItem>

          {/* 金额面值 */}
          <FormItem {...formItemLayout} label='Value'>
            {getFieldDecorator('value', {
              rules: [{
                validator: this.couponValueValidator
              }]
            })(
              <Input
                onChange={(e) => {
                  let value = e.target.value
                  let {store} = this.state
                  let amount = value * store
                  this.setState({value, amount})
                  if (amount > availableAmount) {
                    this.setState({showErr: true})
                  } else {
                    this.setState({showErr: false})
                  }
                }}
                type='number'
                maxLength='50' />
          )}
          </FormItem>

          {/* 优惠券库存数量 */}
          <FormItem {...formItemLayout} label='Store'>
            {getFieldDecorator('initStore', {
              rules: [{
                required: true,
                message: 'Please input store'
              }, {
                validator: this.numberValidator
              }
              ]
            })(
              <Input
                maxLength='50'
                type='number'
                onChange={(e) => {
                  let store = e.target.value
                  let {value} = this.state
                  let amount = value * store
                  this.setState({store, amount})
                  if (amount > availableAmount) {
                    this.setState({showErr: true})
                  } else {
                    this.setState({showErr: false})
                  }
                }} />
            )}
          </FormItem>

          <FormItem {...formItemLayout} label='Amount'>
            {getFieldDecorator('amount')(
              <span className={showErr ? 'err-text' : ''} >{amount}</span>
            )}
          </FormItem>

          {/* 优惠券总额数量  */}
          <FormItem
            {...formItemLayout}
            label='Amount Limit'>
            {getFieldDecorator('haveNoAmountLimit', {
              rules: [{
                required: true,
                message: 'Please select amount limit'
              }]
            })(
              <RadioGroupWrap
                onChange={(e) => this.onChangeRadio(e, 'amountList')}
                list={amountList} />
              )}
          </FormItem>

          {showAmountInput &&
            <FormItem className='limit-input' {...formItemLayout}>
              {getFieldDecorator('minConsumption', {
                rules: [{
                  validator: this.numberValidator
                }]
              })(
                <Input type='number' maxLength='50' />
                  )}
            </FormItem>
          }

          {/*  领取数量 */}
          <FormItem
            {...formItemLayout}
            label='Receive Limit'>
            {getFieldDecorator('haveNoReceiveLimit', {
              rules: [{
                required: true,
                message: 'Please select receive limit'
              }]
            })(
              <RadioGroupWrap
                onChange={(e) => this.onChangeRadio(e, 'reciveList')}
                list={reciveList} />
            )}
          </FormItem>
          {
            showReciveInput &&
            <FormItem
              className='limit-input'
              {...formItemLayout}>
              {getFieldDecorator('maxReceiveTimes', {
                rules: [{
                  validator: this.reciveValidator
                }]
              })(
                <Input type='number' maxLength='50' />
            )}
            </FormItem>
          }
          {/* 优惠券的有效时间 */}
          <FormItem
            {...formItemLayout}
            label='Effective Period'>
            {getFieldDecorator('period', {
              rules: [{
                required: true,
                message: 'Please select effective period'
              }]
            })(
              <RangePicker
                disabledDate={this.disabledStartDate}
                onChange={(e, dateArr) => {
                  this.selecteDate(dateArr)
                }} />
            )}
          </FormItem>
          {/* 优惠券描述 */}
          <FormItem
            {...formItemLayout}
            label={'Introduction'}>
            {
            getFieldDecorator('introduction')(
              <Input.TextArea
                maxLength='500'
                autosize={{ minRows: 6, maxRows: 8 }}
                placeholder='Please Input Introduction'
                style={{width: '700px'}} />
              )
            }
          </FormItem>
        </Form>
        <div className='form-btns'>
          <Button
            onClick={() => actions.routing.push({pathname: '/page-promo-code'})}
          >Back</Button>
          <Button
            className='ml16'
            onClick={this.handleSubmit}
            type='primary'>Submit</Button>
        </div>
      </div>
    </div>
  }
}

let App = Form.create()(Coupon)
export default connect(state => {
  return state.mainModel
})(App)
